﻿using iMES.Core.Extensions.AutofacManager;
using iMES.Entity.DomainModels;
using iMES.Inventory.IRepositories;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Text;


namespace iMES.Inventory.Services
{
    public partial class View_ReceiveServices
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IView_ReceiveReprository _repository;//访问数据库

        [ActivatorUtilitiesConstructor]
        public View_ReceiveServices(
            IView_ReceiveReprository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }

        public override PageGridData<Inventory_Receive> GetPageData(PageDataOptions options)
        {
            // 构建唯一缓存Key
            string cacheKey = $"Inventory_Receive:Page:{options.Page}:Rows:{options.Rows}:Wheres:{options.Wheres ?? ""}:Sort:{options.Sort ?? ""}:Order:{options.Order ?? ""}";

            // 获取Redis连接
            var redis = AutofacContainerModule.GetService<IConnectionMultiplexer>();
            var db = redis.GetDatabase();

            // 查询缓存
            string cacheValue = db.StringGet(cacheKey);
            if (!string.IsNullOrEmpty(cacheValue))
            {
                return JsonConvert.DeserializeObject<PageGridData<Inventory_Receive>>(cacheValue);
            }

            // 缓存没有，查数据库
            var result = base.GetPageData(options);
             
            // 写入缓存，设置过期时间（如10分钟）
            db.StringSet(cacheKey, JsonConvert.SerializeObject(result), TimeSpan.FromMinutes(10));

            return result;
        }
    }
}
